#include "registerwindow.h"
#include "database.h"

#include <QPainter>
#include <QRandomGenerator>
#include <QMessageBox>

RegisterWindow::RegisterWindow(QStackedWidget *stackedWidget, QWidget *parent)
    : QWidget(parent), stackedWidget(stackedWidget)
{
    initUI();
    setupConnections();
    generateCaptcha();
}

void RegisterWindow::initUI()
{
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setSpacing(15);
    mainLayout->setContentsMargins(40, 20, 40, 20);

    QHBoxLayout* usernameLayout = new QHBoxLayout();
    QLabel* usernameLabel = new QLabel("账号:", this);
    usernameLabel->setFixedWidth(60);
    m_usernameInput = new QLineEdit(this);
    m_usernameInput->setPlaceholderText("请输入用户名");
    m_usernameInput->setMinimumWidth(200);
    usernameLayout->addWidget(usernameLabel);
    usernameLayout->addWidget(m_usernameInput);
    usernameLayout->addStretch();

    QHBoxLayout* passwordLayout = new QHBoxLayout();
    QLabel* passwordLabel = new QLabel("密码:", this);
    passwordLabel->setFixedWidth(60);
    m_passwordInput = new QLineEdit(this);
    m_passwordInput->setEchoMode(QLineEdit::Password);
    m_passwordInput->setPlaceholderText("请输入密码");
    m_passwordInput->setMinimumWidth(200);
    passwordLayout->addWidget(passwordLabel);
    passwordLayout->addWidget(m_passwordInput);
    passwordLayout->addStretch();

    QHBoxLayout* surePasswordLayout = new QHBoxLayout();
    QLabel* surePasswordLabel = new QLabel("确认密码:", this);
    surePasswordLabel->setFixedWidth(60);
    m_surePasswordInput = new QLineEdit(this);
    m_surePasswordInput->setEchoMode(QLineEdit::Password);
    m_surePasswordInput->setPlaceholderText("请确认密码");
    m_surePasswordInput->setMinimumWidth(200);
    surePasswordLayout->addWidget(surePasswordLabel);
    surePasswordLayout->addWidget(m_surePasswordInput);
    surePasswordLayout->addStretch();

    QHBoxLayout* captchaLayout = new QHBoxLayout();
    QLabel* captchaLabel = new QLabel("验证码:", this);
    captchaLabel->setFixedWidth(60);

    QVBoxLayout* captchaRightLayout = new QVBoxLayout();
    captchaRightLayout->setSpacing(5);

    m_captchaInput = new QLineEdit(this);
    m_captchaInput->setPlaceholderText("请输入验证码");
    m_captchaInput->setMaxLength(4);
    m_captchaInput->setFixedWidth(200);
    captchaRightLayout->addWidget(m_captchaInput);

    QHBoxLayout* imageLayout = new QHBoxLayout();
    m_captchaLabel = new QLabel(this);
    m_captchaLabel->setFixedSize(100, 40);
    m_refreshCaptchaButton = new QPushButton("刷新", this);
    m_refreshCaptchaButton->setFixedWidth(60);
    imageLayout->addWidget(m_captchaLabel);
    imageLayout->addSpacing(35);
    imageLayout->addWidget(m_refreshCaptchaButton);
    imageLayout->addStretch();
    captchaRightLayout->addLayout(imageLayout);

    captchaLayout->addWidget(captchaLabel);
    captchaLayout->addLayout(captchaRightLayout);
    captchaLayout->addStretch();

    QHBoxLayout* buttonLayout = new QHBoxLayout();
    m_registerButton = new QPushButton("注册", this);
    m_backButton = new QPushButton("返回登录", this);
    m_registerButton->setFixedWidth(100);
    m_backButton->setFixedWidth(100);
    buttonLayout->addStretch();
    buttonLayout->addWidget(m_registerButton);
    buttonLayout->addSpacing(20);
    buttonLayout->addWidget(m_backButton);
    buttonLayout->addStretch();

    mainLayout->addLayout(usernameLayout);
    mainLayout->addLayout(passwordLayout);
    mainLayout->addLayout(surePasswordLayout);
    mainLayout->addLayout(captchaLayout);
    mainLayout->addLayout(buttonLayout);
    mainLayout->addStretch();

    QString buttonStyle = "QPushButton { background-color: #2196F3; color: white; border-radius: 4px; padding: 8px; }"
                          "QPushButton:hover { background-color: #1976D2; }"
                          "QPushButton:pressed { background-color: #0D47A1; }";
    m_registerButton->setStyleSheet(buttonStyle);
    m_backButton->setStyleSheet(buttonStyle);
    m_refreshCaptchaButton->setStyleSheet("QPushButton { border: 1px solid #ccc; border-radius: 4px; }");

    QString inputStyle = "QLineEdit { padding: 6px; border: 1px solid #ccc; border-radius: 4px; }"
                         "QLineEdit:focus { border-color: #2196F3; }";
    m_usernameInput->setStyleSheet(inputStyle);
    m_passwordInput->setStyleSheet(inputStyle);
    m_surePasswordInput->setStyleSheet(inputStyle);
    m_captchaInput->setStyleSheet(inputStyle);
}

void RegisterWindow::setupConnections()
{
    connect(m_registerButton, &QPushButton::clicked, this, &RegisterWindow::onRegisterClicked);
    connect(m_backButton, &QPushButton::clicked, this, &RegisterWindow::onBackClicked);
    connect(m_refreshCaptchaButton, &QPushButton::clicked, this, &RegisterWindow::onRefreshCaptcha);
}

void RegisterWindow::generateCaptcha()
{
    const QString characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    m_currentCaptcha.clear();

    for(int i = 0; i < 4; ++i) {
        int index = QRandomGenerator::global()->bounded(characters.length());
        m_currentCaptcha.append(characters.at(index));
    }

    QImage captchaImage(100, 40, QImage::Format_RGB32);
    captchaImage.fill(Qt::white);
    QPainter painter(&captchaImage);

    QFont font;
    font.setPointSize(20);
    painter.setFont(font);

    for(int i = 0; i < m_currentCaptcha.length(); ++i) {
        painter.setPen(QColor(
            QRandomGenerator::global()->bounded(128),
            QRandomGenerator::global()->bounded(128),
            QRandomGenerator::global()->bounded(128)
            ));
        painter.drawText(QRect(i * 25, 0, 25, 40), Qt::AlignCenter, QString(m_currentCaptcha.at(i)));
    }

    for(int i = 0; i < 6; ++i) {
        painter.setPen(QColor(
            QRandomGenerator::global()->bounded(128, 256),
            QRandomGenerator::global()->bounded(128, 256),
            QRandomGenerator::global()->bounded(128, 256)
            ));
        painter.drawLine(
            QPoint(QRandomGenerator::global()->bounded(100), QRandomGenerator::global()->bounded(40)),
            QPoint(QRandomGenerator::global()->bounded(100), QRandomGenerator::global()->bounded(40))
            );
    }

    m_captchaLabel->setPixmap(QPixmap::fromImage(captchaImage));
}

void RegisterWindow::onRegisterClicked()
{
    QString username = m_usernameInput->text().trimmed();
    QString password = m_passwordInput->text();
    QString surePassword = m_surePasswordInput->text();
    QString captcha = m_captchaInput->text().trimmed();

    if (username.isEmpty() || password.isEmpty() || surePassword.isEmpty()) {
        QMessageBox::warning(this, "提示", "请填写所有字段！");
        return;
    }

    if (password != surePassword) {
        QMessageBox::warning(this, "提示", "两次输入的密码不一致！");
        return;
    }

    if (captcha.isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入验证码！");
        return;
    }

    if (captcha.toLower() != m_currentCaptcha.toLower()) {
        QMessageBox::warning(this, "提示", "验证码错误！");
        generateCaptcha();
        m_captchaInput->clear();
        return;
    }

    if (Database::getInstance()->addUser(username, password))
    {
        QMessageBox::information(this, "提示", "注册成功！");
        stackedWidget->setCurrentIndex(0);
    }
}

void RegisterWindow::onBackClicked()
{
    stackedWidget->setCurrentIndex(0);
}

void RegisterWindow::onRefreshCaptcha()
{
    generateCaptcha();
    m_captchaInput->clear();
}
